package com.wondersgroup.service.impl;

import com.wondersgroup.entity.*;
import com.wondersgroup.mapper.CompanyMapper;
import com.wondersgroup.mapper.PersonMapper;
import com.wondersgroup.mapper.RecordMapper;
import com.wondersgroup.service.PersonService;
import com.wondersgroup.service.RecordService;
import com.wondersgroup.util.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class PersonServiceImpl implements PersonService {


  @Autowired
  private PersonMapper personMapper;

  @Autowired
  private RecordMapper recordMapper;
  @Autowired
  private RecordService recordService;
  @Autowired
  private CompanyMapper companyMapper;

  /**
   * 签退 就证明 已经有签到记录 肯定能查出来数据
   *
   * @param openId
   * @param kssj
   * @param jssj
   * @return
   */
  @Override
  public Map<String, Object> signOut(String openId, String dwid, Date kssj, Date jssj) {
    Map<String, Object> map = new HashMap<>();
    List<Record> recordList = null;
    try {
      // 签退时   根据时间 单位 openId 查询 访问记录
      // 查出来的数据倒叙排列  第一个为最新数据
      recordList = recordService.getRecordByOpenId(openId, dwid, kssj, jssj);
      if (recordList == null || recordList.size() < 1) {
        map.put("code", 500);
        map.put("msg", "无签到记录");
        return map;
      }
      Record latest = recordList.get(0);
      if (latest != null && latest.getQtsj() != null) {
        map.put("code", 201);
        map.put("msg", "已签退过,请重新签到!");
        return map;
      }
      latest.setQtsj(new Date()); //设置 签退时间
      int result = recordService.signOut(latest);
      if (result < 1) {
        map.put("code", 500);
        map.put("msg", "签退失败！");
      } else {
        RecordVo vo = getReCordVo(latest);
        vo = getTmData(vo);
        vo = getRsaData(vo);
        vo.setDwmc(getDwmc(dwid));
        map.put("code", 200);
        map.put("record", vo);
      }
    } catch (Exception e) {
      e.printStackTrace();
      map.put("code", 500);
      map.put("msg", "操作异常！！");
    }
    return map;
  }


  @Override
  public Map<String, Object> isRegister(String openId, String yxbz) {
    Map<String, Object> map = new HashMap<>();
    Person person = personMapper.getPersonByOpenId(openId, yxbz);
    if (person != null) {
      map.put("code", 200);
      map.put("person", person);
    } else {
      map.put("code", 500);
      map.put("msg", "未注册!");
    }
    return map;
  }

  /**
   * 先查record表  没有数据的话 查person表
   *
   * @param openId
   * @return
   * @throws Exception
   */
  @Override
  public Map<String, Object> visit(String openId) throws Exception {
    Map<String, Object> map = new HashMap<>();
    List<Record> recordList = recordMapper.getRecordsByOpenId(openId);
    if (recordList != null && recordList.size() > 0) {
      RecordVo vo = getReCordVo(recordList.get(0));
      vo = getRsaData(vo);
      map.put("code", 200);
      map.put("record", vo);
    } else {
      Person p = personMapper.getPersonByOpenId(openId, "1");
      if (p != null) {
        RecordVo vo = new RecordVo();
        vo.setXm(p.getXm());
        vo.setSjhm(p.getSjhm());
        vo.setZjhm(p.getZjhm());
        vo.setRsaXm(p.getXm());
        vo.setRsaSjhm(p.getSjhm());
        vo.setRsaZjhm(p.getZjhm());
        vo = getRsaData(vo);
        map.put("code", 200);
        map.put("record", vo);
      } else {
        map.put("msg","无签到记录！");
        map.put("code",500);
      }
    }
    return map;
  }


  @Override
  public Map<String, Object> signIn(Record record) throws Exception {
    Map<String, Object> map = new HashMap<>();
    /**
     1. 访客信息不完整  只将信息插入到 访客表（_record）
     2. 访客信息完整   将信息同时插入到  人员信息表（person_info） 和访客表(_record)
     **/
    if (record.getXm() != null && record.getZjhm() != null) {
      // 判断是否注册 未注册 新增一条数据  已注册 更新数据
      Person p = personMapper.getPersonByOpenId(record.getOpenId(), "1");//1为有效
      Person person = new Person();
      person.setId(record.getId());
      person.setOpenId(record.getOpenId());
      person.setXm(record.getXm());
      person.setXb(record.getXb());
      person.setZjlx(record.getZjlx());
      person.setSjhm(record.getSjhm());
      person.setZcsj(record.getDjsj());
      person.setYxbz(record.getYxbz());
      person.setZjhm(record.getZjhm());
      if (p == null) {
        // 未注册   修改时间与 登记时间相同
        person.setXgsj(record.getDjsj());
        personMapper.addPerson(person);
      } else {
        // 已注册  登记时间不变  修改时间为最新时间
        person.setXgsj(new Date());
        person.setYxbz(p.getYxbz());
        personMapper.updatePerson(person);
      }
    }
    recordMapper.addRecord(record);
    //注册成功后 将对象返回
    RecordVo vo = getReCordVo(record);
    vo = getTmData(vo);
    vo = getRsaData(vo);
    vo.setDwmc(getDwmc(record.getDwid()));
    map.put("code", 200);
    map.put("record", vo);
    return map;
  }


  // 转换
  private RecordVo getReCordVo(Record record) {
    RecordVo vo = new RecordVo();
    if (record != null) {
      vo.setId(record.getId());
      vo.setDwid(record.getDwid());
      vo.setOpenId(record.getOpenId());
      vo.setSjhm(record.getSjhm());
      vo.setXm(record.getXm());
      vo.setXb(record.getXb());
      vo.setZjlx(record.getZjlx());
      vo.setZjhm(record.getZjhm());
      vo.setTw(record.getTw());
      vo.setLfsy(record.getLfsy());
      vo.setLfsyqt(record.getLfsyqt());
      vo.setTxrs(record.getTxrs());
      vo.setBz(record.getBz());
      vo.setDjsj(record.getDjsj());
      vo.setQtsj(record.getQtsj());
      vo.setYxbz(record.getYxbz());
      // vo 私有属性
      vo.setRsaXm(record.getXm());
      vo.setRsaSjhm(record.getSjhm());
      vo.setRsaZjhm(record.getZjhm());
    }


    return vo;
  }


  // 脱敏方法
  private RecordVo getTmData(RecordVo vo) {
    //姓名转换
    if (vo.getXm() != null && !vo.getXm().equals("")) {
      String xm = "*" + vo.getXm().substring(1, vo.getXm().length());
      vo.setXm(xm);
    }
    //手机号转换
    if (vo.getSjhm() != null && !vo.getSjhm().equals("")) {
      String phoneNumber = vo.getSjhm().substring(0, 3) + "****" + vo.getSjhm().substring(7, vo.getSjhm().length());
      vo.setSjhm(phoneNumber); // 脱敏
    }
    // 身份证号转换
    if (vo.getZjhm() != null && !vo.getZjhm().equals("")) {
      String zjhm = vo.getZjhm().substring(0, 3) + "***********" + vo.getZjhm().substring(14, vo.getZjhm().length());
      vo.setZjhm(zjhm);
    }
    return vo;
  }


  // 加密方法
  private RecordVo getRsaData(RecordVo vo) throws Exception {
    if (vo.getRsaXm() != null && !vo.getRsaXm().equals("")) {
      System.out.println("转码前：---" + vo.getRsaXm());
      vo.setRsaXm(URLEncoder.encode(vo.getRsaXm(), "UTF-8"));
      System.out.println("转码后：---" + vo.getRsaXm());
      vo.setRsaXm(RsaUtil.getEncData(vo.getRsaXm()));
    }
    if (vo.getRsaSjhm() != null && !vo.getRsaSjhm().equals("")) {
      vo.setRsaSjhm(RsaUtil.getEncData(vo.getRsaSjhm()));
    }
    if (vo.getRsaZjhm() != null && !vo.getRsaZjhm().equals("")) {
      vo.setRsaZjhm(RsaUtil.getEncData(vo.getRsaZjhm()));
    }
    return vo;
  }

  // person --> personVo
  private PersonVo getPersonVo(Person person) {
    PersonVo pvo = new PersonVo();
    if (person != null && !person.equals("")) {
      pvo.setId(person.getId());
      pvo.setOpenId(person.getOpenId());
      pvo.setXm(person.getXm());
      pvo.setXb(person.getXb());
      pvo.setZjlx(person.getZjlx());
      pvo.setZjhm(person.getZjhm());
      pvo.setSjhm(person.getSjhm());
      pvo.setZcsj(person.getZcsj());
      pvo.setXgsj(person.getXgsj());
      pvo.setYxbz(person.getYxbz());
      // vo 私有属性
      pvo.setRsaXm(person.getXm());
      pvo.setRsaZjhm(person.getZjhm());
      pvo.setRsaSjhm(person.getSjhm());
    }
    return pvo;
  }


  private PersonVo getTmPersonVo(PersonVo vo) {
    //姓名转换
    if (vo.getXm() != null && !vo.getXm().equals("")) {
      String xm = "*" + vo.getXm().substring(1, vo.getXm().length());
      vo.setXm(xm);
    }
    //手机号转换
    if (vo.getSjhm() != null && !vo.getSjhm().equals("")) {
      String phoneNumber = vo.getSjhm().substring(0, 3) + "****" + vo.getSjhm().substring(7, vo.getSjhm().length());
      vo.setSjhm(phoneNumber); // 脱敏
    }
    // 身份证号转换
    if (vo.getZjhm() != null && !vo.getZjhm().equals("")) {
      String zjhm = vo.getZjhm().substring(0, 3) + "***********" + vo.getZjhm().substring(14, vo.getZjhm().length());
      vo.setZjhm(zjhm);
    }
    return vo;
  }


  private PersonVo getRsaPersonVo(PersonVo vo) throws Exception {
    if (vo.getRsaXm() != null && !vo.getRsaXm().equals("")) {
      vo.setRsaXm(URLEncoder.encode(vo.getRsaXm(), "UTF-8"));
      vo.setRsaXm(RsaUtil.getEncData(vo.getRsaXm()));
    }
    if (vo.getRsaSjhm() != null && !vo.getRsaSjhm().equals("")) {
      vo.setRsaSjhm(RsaUtil.getEncData(vo.getRsaSjhm()));
    }
    if (vo.getRsaZjhm() != null && !vo.getRsaZjhm().equals("")) {
      vo.setRsaZjhm(RsaUtil.getEncData(vo.getRsaZjhm()));
    }
    return vo;
  }


  @Override
  public List<Person> getAllPersons(String yxbz) {
    return personMapper.getAllPersons(yxbz);
  }

  @Override
  public RecordVo getLatestRecord(String openId, String dwid) throws Exception {
    RecordVo vo = new RecordVo();
    Date kssj = com.wondersgroup.util.TimeUtil.getStartTime(new Date());
    Date jssj = com.wondersgroup.util.TimeUtil.getEndTime(new Date());
    List<Record> recordList = recordMapper.getRecordByOpenId(openId, dwid, kssj, jssj);
    if (recordList != null && recordList.size() > 0) {
      vo = getReCordVo(recordList.get(0));
      vo = getTmData(vo);
      vo = getRsaData(vo);
    }
    return vo;
  }


  //获取 单位名称
  private String getDwmc(String dwid) {
    String result = null;
    // 根据 dwid 获取单位名称
    Company company = companyMapper.getCompanyById(dwid);
    if (company != null) {
      result = company.getDwmc();
    }
    return result;
  }

}
